package cn.net.isir.controller.miniprogram;

import cn.net.isir.common.CacheObjectManager;
import cn.net.isir.common.RequestObject;
import cn.net.isir.common.ResultObject;
import cn.net.isir.common.TokenManager;
import cn.net.isir.entity.Message;
import cn.net.isir.entity.MessageReadStatus;
import cn.net.isir.entity.Organizations;
import cn.net.isir.entity.Shop;
import cn.net.isir.service.*;
import cn.net.isir.service2.MinipIndexDataService;
import cn.net.isir.service2.ShopService;
import cn.net.isir.utils.AppRequestUtils;
import cn.net.isir.utils.MapUtils;
import cn.net.isir.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * Minip主页数据显示
 *
 * @author liuxubo
 * @filename Index.java
 * @package cn.net.isir.controller.miniprogram
 * @email lxb@isir.net.cn
 * @date 2019/02/26
 * @comment
 * @since 1.8
 */
@RestController
@RequestMapping("/minip/index")
@SuppressWarnings("all")
public class MinipIndexController {

    @Resource
    private MinipIndexDataService minipIndexDataService;
    @Resource
    private TurnShopService turnShopService;
    @Resource
    private CRMUserManagerService crmUserManagerService;
    @Resource
    private MinipIndexMessageService minipIndexMessageService;
    @Resource
    private TurnService turnService;
    @Resource
    private MessageService messageService;
    @Resource
    private MessageReadStatusService messageReadStatusService;
    @Resource
    private ShopService shopService;

    /**
     * 首页数据查询
     *
     * @param obj 数据
     * @return
     */
    @RequestMapping(value = "/data", method = RequestMethod.GET)
    public ResultObject getData(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        //声明返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }

        ro.setResult(200);
        ro.setMessage("success");
        Map indexData = minipIndexDataService.getIndexData(userId,
                crmUserManagerService.getTurnedShopIds(),
                crmUserManagerService.getTimeRangeList(userId));
        // 最新消息标题
        indexData.put("msgTitle", minipIndexMessageService.getIndexMessage().getTitle());
        ro.setObject(indexData);
        return ro;
    }

    /**
     * 获取未结转店铺列表
     *
     * @return
     */
    @RequestMapping(value = "/noturnshoplist", method = RequestMethod.GET)
    public ResultObject getNoTurnShopList(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        //声明返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }

        ro.setResult(200);
        ro.setMessage("success");
        ro.setObject(minipIndexDataService.getNoTurnShopList(userId,
                crmUserManagerService.getTurnedShopIds(),
                crmUserManagerService.getTimeRangeList(userId)));
        return ro;
    }

    /**
     * 店铺每日统计列表查询
     *
     * @return
     */
    @RequestMapping(value = "/dayshoplist", method = RequestMethod.GET)
    public ResultObject getDayShopList(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        columns.add("shopId");
        //声明返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }
        ro.setResult(200);
        ro.setMessage("success");
        ro.setObject(minipIndexDataService.getEveryDayFlow(String.valueOf(params.get("shopId")), userId,
                crmUserManagerService.getTurnedShopIds(),
                crmUserManagerService.getTimeRangeList(userId)));
        return ro;
    }

    /**
     * 日活未达标店铺列表查询
     *
     * @return
     */
    @RequestMapping(value = "/daynoliveshoplist", method = RequestMethod.GET)
    public ResultObject getDayNoLiveShopList(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        //声明返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }
        ro.setResult(200);
        ro.setMessage("success");
        ro.setObject(minipIndexDataService.getDayNoLiveShopList(userId,
                crmUserManagerService.getTurnedShopIds(),
                crmUserManagerService.getTimeRangeList(userId)));
        return ro;
    }


    /**
     * 通知列表查询
     *
     * @return
     */
    @RequestMapping(value = "/msglist", method = RequestMethod.GET)
    public ResultObject getMsgList(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        columns.add("pageNum");
        columns.add("pageSize");
        //生命返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }
//        ro.setResult(200);
//        ro.setMessage("success");
        Integer pageNo = Integer.parseInt(String.valueOf(params.get("pageNum")));
        Integer pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        String content = params.get("content") == null ? null : String.valueOf(params.get("content"));
//        ro.setObject(minipIndexMessageService.findMsgList(pageNo, pageSize));
//        return ro;

        Organizations org = crmUserManagerService.getOrgByUserId(userId);
        List<Organizations> pOrgList = crmUserManagerService.getParentsOrgByOrgId(org.getId());
//        String pOrgOR = StringUtils.collectionsToCommas();
        String pOrgOR = StringUtils.collectionsToCommas(pOrgList, Organizations::getId);
        if (StringUtils.isNotBlank(pOrgOR)) {
            pOrgOR = pOrgOR.replace(",", "|");
        }
        PageInfo<Message> info = messageService.getMyOrgMessage(pOrgOR, content,
                pageNo, pageSize, userId);
        return new ResultObject(200, "success", info);
    }


    /**
     * 通知详情查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/msginfo")
    public ResultObject getMsgInfo(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        columns.add("id");
        //生命返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }

        String msgId = String.valueOf(params.get("id"));
        Message msgInfo = messageService.selectByPrimaryKey(msgId);
        if (msgInfo == null) {
            return new ResultObject(500, "fail", null);
        }


        Map<String, Object> map = new HashMap<>();
        //获取主键id
        map.put("id", msgInfo.getId());
        //获取标题title
        map.put("title", msgInfo.getTitle());
        //获取发送者sender
        map.put("sender", msgInfo.getCreater());
        //获取发送时间sendTime
        map.put("sendTime", msgInfo.getPublishTime());
        //获取内容content
        map.put("content", msgInfo.getContent());

        ro.setResult(200);
        ro.setMessage("success");
        ro.setObject(map);

        // 保存已读状态
        MessageReadStatus readStatus = new MessageReadStatus();
        readStatus.setMsgId(msgId);
        readStatus.setUserId(userId);
        MessageReadStatus readStatus2 = messageReadStatusService.selectOne(readStatus);
        if (readStatus2 == null) {
            readStatus.setReadTime(new Date());
            messageReadStatusService.insert(readStatus);
        }

        return ro;
    }

    /**
     * 结转记录
     *
     * @param obj
     * @return
     */
    @RequestMapping(value = "/turnhistory")
    public ResultObject getTurnHistory(RequestObject obj) {
        //声明参数解码后的储存变量
        Map<String, Object> params = new HashMap<>();
        //需要检查的字段名
        List<String> columns = new ArrayList<>();
        columns.add("key");
        //生命返回值
        ResultObject ro = AppRequestUtils.parametersCheck(obj, params, columns);
        //检查失败则返回缺失的字段提示
        if (ro.getResult() != 200) {
            return ro;
        }
        // 获取小程序传递过来的key
        String key = String.valueOf(params.get("key"));
        // 从缓存中,根据key查询获取到的userId
        String userId = CacheObjectManager.minipCRMKey.get(key);
        if (userId == null) {
            return new ResultObject(502, "need login.", null);
        }
        ro.setResult(200);
        ro.setMessage("success");
        List<Map<String, Object>> turnShopList = turnService.getTurnHistoryList(userId);
        for (Map<String, Object> turnShop : turnShopList){
            String shopId = turnShop.get("shopId").toString();
            Shop shop = shopService.selectByPrimaryKey(shopId);
            turnShop.put("shopName",shop.getName());
            BigDecimal amount = (BigDecimal)turnShop.get("amount");
            turnShop.put("amount",amount.setScale(3, BigDecimal.ROUND_HALF_UP));
//            turnShop.remove("shopId",shopId);
        }
        ro.setObject(turnShopList);
        return ro;
    }
}
